-- 将到达ack容忍时间后仍未收到ack的消息从待ack的zset移动至待republish的zset

local to_ack_zset = KEYS[1];
local to_republish_zset = KEYS[2];
local nowTimeMillis = ARGV[1];

-- 查询待ack的zset元素个数
local checkNo = redis.call('ZCARD', to_ack_zset)
-- 如果没有元素，直接返回
if (tonumber(checkNo) > 0)
then
    -- 批量获取满足条件的元素
    local member = redis.call('ZRANGEBYSCORE', to_ack_zset, 0, tonumber(nowTimeMillis));
    local count = redis.call('ZCOUNT', to_ack_zset, 0, tonumber(nowTimeMillis));
    -- 如果空表直接return
    if next(member) == nil
    then
        return 0
    else
        -- 迭代member做移动操作
        for key, value in ipairs(member)
        do
            local zscore = redis.call('ZSCORE', to_ack_zset, value);
            if tonumber(nowTimeMillis) >= tonumber(zscore)
            then
                redis.call('ZREM', to_ack_zset, value) ;
                redis.call('ZADD', to_republish_zset, tonumber(nowTimeMillis), value);
            end
        end
        return count
    end
else
    return 0
end
